package com.tencreat.mall.controller.app;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencreat.common.annotation.Log;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.model.*;
import com.tencreat.common.enums.*;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.LogisticsUtils;
import com.tencreat.common.utils.SecurityUtils;
import com.tencreat.common.utils.TenCreatUtil;
import com.tencreat.domain.account.MallStore;
import com.tencreat.domain.mall.*;
import com.tencreat.domain.mall.dto.*;
import com.tencreat.domain.mall.vo.*;
import com.tencreat.service.account.IMallStoreService;
import com.tencreat.service.mall.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Api(tags = {"2-APP商城商品接口"})
@RequestMapping("/api/goods")
@RestController
@RequiredArgsConstructor
public class MallGoodsController extends BaseController {

    private final IMallGoodsService mallGoodsService;//商品基本信息
    private final IMallOrderService mallOrderService;//订单
    private final IMallAddressService mallAddressService;//收货地址
    private final IMallCommentService mallCommentService;//评论
    private final IMallOrderGoodsService mallOrderGoodsService;//订单商品
    private final IMallCouponService mallCouponService;//优惠券信息及规则
    private final IMallGoodsNormsService goodsNormsService;//商品规格参数
    private final IMallStoreService mallStoreService;//店铺信息
    /**
     * 新增评论
     */
    @ApiOperation(value = "新增评论")
    @PostMapping(value = "/comment/add")
    public HttpResult add(@RequestBody MallCommentDTO mallCommentDTO) {
        String orderSn = mallCommentDTO.getOrderSn();
        mallCommentDTO.setOrderGoodsSn(mallCommentDTO.getOrderSn());
        // 查询订单信息
        MallOrderGoods goods = mallOrderGoodsService.lambdaQuery().eq(MallOrderGoods::getOrderSn, mallCommentDTO.getOrderSn())
                .eq(MallOrderGoods::getGoodsId, mallCommentDTO.getGoodsId()).eq(MallOrderGoods::getNormsId, mallCommentDTO.getNormsId()).eq(MallOrderGoods::getOrderGoodsSn, mallCommentDTO.getOrderGoodsSn()).one();
        if (goods != null && goods.getOrderGoodsSn() != null) {
            mallCommentDTO.setOrderGoodsSn(goods.getOrderGoodsSn());
        }
        mallCommentService.insertMallComment(mallCommentDTO);
        //修改评论修改订单商品状态
        mallOrderGoodsService.updateOrderTypeByGoodsNorms(orderSn, mallCommentDTO.getGoodsId(), mallCommentDTO.getNormsId(), OrderStatus.OK.getValue(), null);
        return HttpResult.ok();
    }


    @ApiOperation(value = "商品列表 集成 搜索 推荐商品")
    @PostMapping("/list")
    @Deprecated
    @ApiIgnore
    public HttpResult<IPage<MallGoodsListVO>> list(@RequestBody MallGoodsSearchDTO mallGoodsSearchPo) {

        return HttpResult.ok(mallGoodsService.apiList(mallGoodsSearchPo));
    }



    @ApiOperation(value = "商品详情")
    @PostMapping("/good_info")
    public HttpResult<MallGoodsDetailsVO> goodInfo(@RequestBody ReqIdParam idParam) {
        return HttpResult.ok(mallGoodsService.goodInfoById(idParam));
    }



    @ApiOperation(value = "店铺详情")
    @PostMapping("/store_info")
    public HttpResult<MallGoodsDetailsVO> storeInfo(@RequestBody ReqIdParam idParam) {
        return HttpResult.ok(mallStoreService.storeInfo(idParam));
    }


    @ApiOperation(value = "预下单")
    @PostMapping("/budget")
    public HttpResult<ResOrderMallBudgetVO> budget(@RequestBody OrderMallBudgetDTO orderMallBudgetVO) {
        return mallOrderService.budget(orderMallBudgetVO, getLoginCheck());
    }

    /**
     * 商品提交订单
     *
     * @return ResOrderMallSubmit
     * @author huangwei
     * @date 2021年9月6日
     */
    @PostMapping("/submit")
    @ApiOperation(value = "商品提交订单")
    public HttpResult<ResOrderMallSubmitVO> submit(@Valid @RequestBody OrderMallSubmitDTO order) {
        return mallOrderService.submit(order, getLoginCheck());
    }

    /**
     * 订单列表
     *
     * @Author wangbingcheng
     * @Date 2021年09月13日
     * @Return
     */   @PostMapping("/order_list")
    @ApiOperation(value = "订单列表")
    public HttpResult<IPage<ResOrderGoodsVO>> orderList(@RequestBody IdAndPage idParam) {
        return mallOrderService.orderList(idParam, getLoginCheck());
    }


    @PostMapping("/queryCommentPage")
//    @ApiOperation(value = "查询商品评价分页列表 common参数需传递商品的商品id")
    @ApiOperation(value = "查询商品评价分页列表 ")
    public HttpResult<IPage<ResMallCommentVO>> queryCommentPage(@RequestBody ReqStringParam param) {
        IPage<ResMallCommentVO> resMallCommentVOIPage=mallCommentService.queryPage(param);

        return HttpResult.ok(resMallCommentVOIPage);
    }



    //@PostMapping("/delAppOrder")
    @ApiOperation(value = "删除订单")
    public HttpResult<Boolean> delAppOrder(@RequestBody ReqIdParam param) {
        return mallOrderService.delAppOrder(param);
    }


    /****
     * 将用户状态以及订单状态改为取消支付
     * @param param
     * @return
     */
    @PostMapping("/cancelPayOrder")
    @ApiOperation(value = "取消订单（取消支付订单）")
    public HttpResult<Boolean> cancelPayOrder(@RequestBody ReqIdParam param) {
        return mallOrderService.cancelPayOrder(param);
    }


    /**
     * 订单详情
     *
     * @param idParam
     * @Author wangbingcheng
     * @Date 2021年09月13日
     * @Return
     */
    @PostMapping("/order_info")
    @ApiOperation(value = "订单详情")
    public HttpResult<ResOrderGoodsVO> orderInfo(@RequestBody ReqIdParam idParam) {
        return mallOrderService.orderInfo(idParam, getLoginCheck());
    }

    /**
     * 确认订单
     *
     * @Author wangbingcheng
     * @Date 2021年09月30日
     * @Return
     */
    @PostMapping("/confirm_order")
    @ApiOperation(value = "确认订单,用户确认收货|用户核销订单")
    public HttpResult<Boolean> confirmOrder(@RequestBody ReqIdParam idParam) {
        return mallOrderService.confirmOrder(idParam, getLoginCheck());
    }

    /**
     * 地址列表
     *
     * @return
     */
    @ApiOperation(value = "地址列表")
    @PostMapping("/addressList")
    public HttpResult<List<MallAddress>> addressList() {
        return HttpResult.ok(mallAddressService.lambdaQuery().eq(MallAddress::getUuid, getUuid()).list());
    }

    /**
     * 默认地址
     *
     * @return
     */
    @ApiOperation(value = "默认地址")
    @PostMapping("/defaultAddress")
    public HttpResult<MallAddress> addressData() {
        return HttpResult.ok(mallAddressService.lambdaQuery().eq(MallAddress::getUuid, getUuid()).eq(MallAddress::getIsDefault, 1).one());
    }

    /**
     * 添加地址
     *
     * @param
     * @return
     */
    @PostMapping("/addAddress")
    @ApiOperation(value = "添加地址")
    public HttpResult<Boolean> addAddress(@RequestBody MallAddressDTO mallAddressDTO) {
        mallAddressService.addAddress(mallAddressDTO, getUuid());
        return HttpResult.ok(true);
    }

    /**
     * 设置默认地址
     *
     * @param
     * @return
     */
    @PostMapping("/setDefaultAddress")
    @ApiOperation(value = "设置默认地址")
    public HttpResult<Boolean> setDefaddAddress(@RequestBody ReqIdParam idParam) {
        return HttpResult.ok(mallAddressService.insertDefMallAddress(idParam, getLoginCheck()) > 0);
    }

    /**
     * 删除地址
     *
     * @param
     * @return
     */
    @PostMapping("/delAddress")
    @ApiOperation(value = "删除地址")
    public HttpResult<Boolean> addAddress(@RequestBody ReqIdParam idParam) {
        return HttpResult.ok(mallAddressService.deleteMallAddressById(idParam) > 0);
    }

    /**
     * 修改地址
     *
     * @param
     * @return
     */
    @PostMapping("/updateAddress")
    @ApiOperation(value = "修改地址")
    public HttpResult<Boolean> updateAddress(@RequestBody MallAddressDTO mallAddressDTO) {
        return HttpResult.ok(mallAddressService.updateMallAddress(mallAddressDTO) > 0);
    }

    /**
     * 优惠券列表
     *
     * @return
     */
    @PostMapping("/couponUserList")
    @ApiOperation(value = "优惠券列表")
    public HttpResult<List<MallCouponUser>> couponUserList(@RequestBody List<ResOrderMallGoodsVO> goods) {
        return HttpResult.ok(mallCouponService.couponUserList(goods, getUuid()));
    }

    @ApiOperation(value = "商品详情")
    @PostMapping("/detail")
    @ApiIgnore
    public HttpResult<ResGoodsDetailVO> list(@RequestBody ReqIdParam id) {
        return HttpResult.ok(mallGoodsService.queryInfoByGoodsSn(id, getLoginCheck()));
    }


    @PostMapping("/checkMoney")
    @ApiOperation(value = "验证金额")
    @ApiIgnore
    public HttpResult<ResCheckMoneyVO> checkMoney(@Valid @RequestBody OrderMallSubmitDTO order) {
        return HttpResult.ok(mallOrderService.checkMoney(order, getLoginCheck()));
    }




    @ApiOperation(value = "查看物流")
    @GetMapping("/checkLogistics")
    public HttpResult<?> checkLogistics(@ApiParam("快递单号") @RequestParam String no) {
        return LogisticsUtils.checkLogistics(no);
    }

    /**
     * 删除订单
     */
    @ApiOperation(value = "删除订单")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public HttpResult<Boolean> remove(@RequestBody ReqIdsParam ids) {
        return to(mallOrderService.deleteMallOrderByIds(ids));
    }

    @GetMapping("/order_count")
    @ApiOperation(value = "订单数量")
    public HttpResult<ResOrderCountVO> orderCountByOrderSn(){
        return mallOrderService.orderCount(SecurityUtils.getLoginUser());
    }

    /**
     * 描述信息  拨号接口
     * @Author yaoruiqi
     * @Date: 2023/10/11 02:49
     */
    @ApiOperation(value = "拨号接口")
    @PostMapping("/call")
    public   HttpResult<String> call(@RequestBody ReqIdParam idParam){
        return mallStoreService.getMobileById(idParam.getId());
    }


    /**
     * 描述信息  店铺核销订单列表
     * @Author yaoruiqi
     * @Date: 2023/11/02 08:00
     */
    @ApiOperation(value = "店铺核销订单列表")
    @PostMapping("/storeOrderList")
    public HttpResult<IPage<MallOrder>> list(@RequestBody MallOrder mallOrder) {
        Page<MallOrder> page = new Page<>(mallOrder.getPageNum(), mallOrder.getPageSize());
        mallOrder.setUserId(getUuid());
        return HttpResult.ok(mallOrderService.storeOrderList(page,mallOrder));
    }

    /**
     * 描述信息  店铺核销订单
     * @Author yaoruiqi
     * @Date: 2023/11/03 10:35
     */

    @PostMapping("/verification_order")
    @ApiOperation(value = "店铺核销订单")
    public HttpResult<Boolean> verification(@RequestBody ReqIdParam idParam) {
        MallStore mallStore = mallStoreService.lambdaQuery().eq(MallStore::getUuid, getUuid()).one();
        if (mallStore!=null){
            idParam.setStoreId(mallStore.getId());

        }else {
            HttpResult.error("无效店铺");
        }

        return mallOrderService.verification(idParam, getLoginCheck());
    }


    /**
     * 描述信息  扫码支付
     * @Author yaoruiqi
     * @Date: 2023/11/17 04:22
     */
    @PostMapping("/submitOffline")
    @ApiOperation(value = "扫码生成订单")
    public HttpResult<ResOrderMallSubmitVO> submitOffline(@RequestBody MallOrder mallOrder){
        if (mallOrder.getActualPrice()==null){
            HttpResult.error("请输入支付价格！");
        }

        mallOrder.setOrderPrice(mallOrder.getActualPrice());
        mallOrder.setStoreId(mallOrder.getStoreId());
        mallOrder.setOrderSn(TenCreatUtil.getOrderNo());
        mallOrder.setOrderStatus(OrderStatus.PAY);
        mallOrder.setOrderType(OrderType.QR_CODE_ORDER);
        mallOrder.setStatusUser(UserOrderStatus.WAIT_PAY);
        mallOrder.setStatusShop(ShopOrderStatus.PAY);
        mallOrder.setCreateTime(LocalDateTime.now());
        mallOrder.setVerificationOrder(1);
        mallOrder.setConsumerRoll(mallOrder.getActualPrice());
//        mallOrder.setOrderType(OrderType.STORE);
        mallOrder.setGoodsId(0L);
        return mallOrderService.submitOffline(mallOrder);
    }


}
